"""
约苗HPV 抢苗
"""
import requests
import itchat
import time
from loguru import logger

class YueMiao:
    jiu_jia_infos_=[]
    has_send_hospital_=[]
    to_room=[]
    now_time=''

    #初始化
    def Init(self):
        self.LoadHasSendHospital()
        logger.add("file_{time}.log")  
        itchat.auto_login(hotReload=True)
        self.to_room = itchat.search_chatrooms(name='测试群')                                      #群聊名称

    #加载以及发送过的医院
    def LoadHasSendHospital(self):                                                      
        try:
            file = open('hassendhospital.txt', 'r', encoding='utf-8')
            self.has_send_hospital_=file.readlines()
            file.close()
        except FileNotFoundError:
            logger.error("File is not found.")
        except PermissionError:
            logger.error("You don't have permission to access this file.")

    #拼接发送到群里的连接
    def CombiningStr(self,name:str,address:str,stopSubscribe:bool,code:int,depaVaccId:int):
        result_time='检测时间:'+self.now_time+'\n'
        hospital_name='检测医院:'+name+'\n'
        hospital_address='医院地址:'+address+'\n'
        hospital_stopSubscribe=''
        if stopSubscribe == False:
            hospital_stopSubscribe='检测状态:可预约\n'
        else:
            hospital_stopSubscribe='检测状态:不可预约\n'
        hospital_url='链接:'+'https://wx.scmttec.com/index.html#/vaccines?vaccCode=8803&depaCode='+str(code)+'&vaccId='+str(depaVaccId)
        return hospital_stopSubscribe+result_time+hospital_name+hospital_address+hospital_url

    #向群里发送连接
    def SendWechat(self):
        file = open('hassendhospital.txt', 'a', encoding='utf-8')
        for i in self.jiu_jia_infos_:
            msg=''
            has_send=str(i['code'])+' '+str(i['depaVaccId'])+'\n'
            if 'stopSubscribe' in i and i['stopSubscribe']==0 and has_send not in self.has_send_hospital_:
                msg=self.CombiningStr(i['name'],i['address'],i['stopSubscribe'],i['code'],i['depaVaccId'])
                itchat.send(msg,toUserName=self.to_room[0]['UserName'])
                logger.info('向群里发送了 '+i['name'])
                self.has_send_hospital_.append(has_send)
                file.write(has_send)
        file.close()

    #访问获取
    def GetCityAllJiuJia(self):
        url = 'https://wx.scmttec.com/department/department/getDepartments.do?offset=0&limit=20&name=&regionCode=5101&isOpen=1&longitude=&latitude=&sortType=1&vaccineCode=&customId=3'
        headers={
        #'tk':'wxtoken:f7e83b5d2601fde87d95770a54d144e2_3c9e8b62f2a9e046ab2248b1bfa1eee6',
        #'Cookie': 'UM_distinctid=17d61b72629bd4-09379e733d29fb-61263e23-13c680-17d61b7262a2aa; _xxhm_=%7B%22id%22%3A22939745%2C%22mobile%22%3A%2213198728370%22%2C%22nickName%22%3A%22add+oil%22%2C%22headerImg%22%3A%22http%3A%2F%2Fthirdwx.qlogo.cn%2Fmmopen%2FGOkHdhP0ZicwF0ddV3OC86jYkjJe7IE38Z2QL1Xks6NChpfeD1yDnXto1heY8ggajurjPAHBV1RrS70k0KwUFtNfcFHhweSOK%2F132%22%2C%22regionCode%22%3A%22510107%22%2C%22name%22%3A%22%E6%96%87*%22%2C%22uFrom%22%3A%22depa_vacc_detail%22%2C%22wxSubscribed%22%3A1%2C%22birthday%22%3A%221997-11-12+02%3A00%3A00%22%2C%22sex%22%3A2%2C%22hasPassword%22%3Afalse%2C%22birthdayStr%22%3A%221997-11-12%22%7D; CNZZDATA1261985103=1734574061-1638017384-%7C1640184040; _xzkj_=wxtoken:f7e83b5d2601fde87d95770a54d144e2_3c9e8b62f2a9e046ab2248b1bfa1eee6',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat'
        }

        try:
            response = requests.get(url,headers=headers,timeout=1)
            rejson=response.json()
        except Exception as e:
            logger.error(e)
            return

        self.now_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        if rejson['code']=='0000':
            self.jiu_jia_infos_=rejson['data']['rows']
        else:
            logger.error(rejson['msg'])

if __name__ == '__main__':
    yuemiao=YueMiao()
    yuemiao.Init()
    count=1
    while True:
        yuemiao.GetCityAllJiuJia()
        yuemiao.SendWechat()
        time.sleep(5)
        logger.info('第'+str(count)+'次检测')
        count=count+1